package com.gw.booking.service;


import com.gw.booking.entity.RandomNumber;
import org.apache.commons.lang.StringUtils;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

@Service
public class RandomNumberService {

    /**
     * 生成0-99的序号
     */
	public String getRandomNumber(Session session, String type){
		RandomNumber randomNumber = (RandomNumber) session.createCriteria(RandomNumber.class)
				.add(Restrictions.eq("type", type))
				.setLockMode(LockMode.UPGRADE_NOWAIT)
				.uniqueResult();
		
		if(randomNumber != null){
			randomNumber.setNumber(randomNumber.getNumber() + 1);
			session.update(randomNumber);
		}else{
			randomNumber = new RandomNumber();
			randomNumber.setNumber(0);
			randomNumber.setType(type);
			session.save(randomNumber);
		}
		
		return StringUtils.leftPad(randomNumber.getNumber() % 100 + "", 2, "0");
	}
}
